(function () {

    /*
     * 该文件在core.js文件后面引入
     */
    /**
     * 1. 根据名称，模糊查询图层数据
     * @param options
     * {
     *      keyword: '', //【必选】关键字
     *      layerIds: [] // 【可选】根据ID数组,指定查询特定的图层；不指定，则查询全部图层
     *  }
     * @param callback   // 成功回调
     *
     * 使用示例【创建MapApp后，可通过app进行调用】
     * ---------------------------------------------------
     MapApp.create(function (app) {
        app.ext_queryLayerByName({keyword: '房', layerIds: ['9c4ee658-7054-49d4-aaba-045da355ba3c']}, function (rs) {
            console.log(rs);
        });
    });
     * ---------------------------------------------------
     */
    MapApp.prototype.ext_queryLayerByName = function (options, callback) {
        var app = this;
        _queryLayerByName(app, options.keyword || '', callback, options.layerIds || []);
    };

    /**
     *-----------------------------------------------------
     */
    function _queryLayerByName(app, keyword, callback, layerIds) {
        var data = {
            where: " name like '%" + keyword + "%'",
            maxFeatures: 1000,// 最大数
            returnGeometry: true,
            spatialFilterType: 'INTERSECTS'
        };

        var layersArr = [];

        if (layerIds && layerIds instanceof Array && layerIds.length > 0) {
            layerIds.forEach(function (id) {
                layersArr.push({
                    layerId: id,
                });
            });
        } else {
            var list = app.getOverlayLayerManager().getLayers();
            var flatTree = function(list) {
                list.forEach(function (el) {
                    var vis = el.isVisible();
                    var hasChildren = (typeof el.getLayers === 'function');
                    if (hasChildren) {
                        var layers = el.getLayers();
                        flatTree(layers);
                    } else {
                        if (vis) {
                            var source = el.getSource();
                            var id = source._options.originLayerId;
                            if (id) {
                                layersArr.push({layerId: id});
                            }

                        }
                    }
                });
            };
            flatTree(list);
        }

        var qUrl = window.globalConfig.getApiBasePath() + "/queryService/query";
        data.layers = layersArr;

        var postData = {
            token: window.globalConfig.getToken(),
            param: JSON.stringify(data)
        };

        var onSuccess = function(data) {
            var layers = data.layers;
            if (callback) {
                callback(layers);
            } else {
                throw "未传入callback函数！";
            }
        };

        var onError = function(error) {
            console.log(error);
        };

        _post(qUrl, postData, onSuccess, onError);
    }
    /**
     * 通用工具封装
     */
    /**
     * ---------ajax 请求方法--------------------------------------------------
     */
    function _get(url, success, error) {
        _ajax('GET', url, null, true, success, error);
    };

    function _post(url, data, success, error) {
        _ajax('POST', url, data, true, success, error);
    };

    function _getAwait(url, success, error) {
        _ajax('GET', url, null, false, success, error);
    };

    function _postAwait(url, data, success, error) {
        _ajax('POST', url, data, false, success, error);
    };

    function _getAwaitText(url, success, error) {
        _ajax('GET', url, null, false, success, error, true);
    };

    function _ajax(type, url, data, async, success, error, isReturnText) {
        var xhr = new XMLHttpRequest();
        xhr.open(type, url, async);
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                if (xhr.status >= 200 && xhr.status < 300) {
                    if (success) {
                        var rt = xhr.responseText;
                        if (rt) {
                            if (isReturnText) {
                                success(rt);
                            } else {
                                success(JSON.parse(rt));
                            }
                        } else {
                            success();
                        }
                    }
                } else {
                    if (error) {
                        error();
                    }
                }
            }
        };
        if (type === "GET") {
            data = null;
        } else {
            data = _convertToFormData(data);
        }
        setTimeout(function () {
            xhr.send(data);
        }, 30);
    };

    function _convertToFormData(data) {
        var formData = new FormData();
        for (var key in data) {
            formData.append(key, data[key]);
        }
        return formData;
    }

})();